package com.starbaba.pushservice.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.http.HttpClientUtil;
import com.base.common.http.model.FormData;
import com.base.common.http.model.HttpResult;
import com.base.common.http.model.PostData;
import com.base.common.log.LogService;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.model.network.Phead;
import com.starbaba.model.utils.JSONUtils;
import com.starbaba.model.utils.ZipUtil;
import com.starbaba.pushservice.model.PushMessageVO;
import com.starbaba.pushservice.service.PushMessageService;
import com.tuanzi.server.loan_base.model.db.PushMessageTask;

@SuppressWarnings({"deprecation", "rawtypes"})
@Component
public class PushMessageServiceImpl implements PushMessageService {

	private static BaseDao dao = new BaseDao(Constant.POOL_LIFE);
	
	@Override
	public void showPage(Map<String, Object> paramsMap) {
	}

	@Override
	public List getList(Integer start, Integer length, PageResponse pageResponse, Map<String, Object> paramsMap) {
		
		String message = (String) paramsMap.get("message");
		String pushcontent = (String) paramsMap.get("pushcontent");
		String platfrom = (String) paramsMap.get("platfrom");
		String status = (String) paramsMap.get("status");
		String createtime_start = (String) paramsMap.get("createtime_start");
		String createtime_end = (String) paramsMap.get("createtime_end");
		String pushtime_start = (String) paramsMap.get("pushtime_start");
		String pushtime_end = (String) paramsMap.get("pushtime_end");
		
		StringBuilder sql_list = new StringBuilder("SELECT * FROM push_message_record WHERE 1=1 ");
		StringBuilder sql_total = new StringBuilder("SELECT count(1) FROM push_message_record WHERE 1=1 ");

		if (message != null) {
			sql_list.append("and (android_content like %"+ message +"% OR ios_content like %" + message + "%)");
			sql_total.append("and (android_content like %"+ message +"% OR ios_content like %" + message + "%)");
		}
		if (pushcontent != null) {
			sql_list.append("and content = '" + pushcontent + "' ");
			sql_total.append("and content = '" + pushcontent + "' ");
		}
		if (platfrom != null) {
			sql_list.append("and platfrom = '" + platfrom + "' ");
			sql_total.append("and platfrom = '" + platfrom + "' ");
		}
		if (status != null) {
			sql_list.append("and status = '"+status+"' ");
			sql_total.append("and status = '"+status+"' ");
		}
		if (createtime_start != null) {
			sql_list.append("and createtime >= '"+ createtime_start +" 00:00:00' ");
			sql_total.append("and createtime >= '"+ createtime_start +" 00:00:00' ");
		}
		if (createtime_end != null) {
			sql_list.append("and createtime <= '"+ createtime_end +" 23:59:59' ");
			sql_total.append("and createtime <= '"+ createtime_end +" 23:59:59' ");
		}
		if (pushtime_start != null) {
			sql_list.append("and sendtime >='"+pushtime_start+" 00:00:00' ");
			sql_total.append("and sendtime >='"+pushtime_start+" 00:00:00' ");
		}
		if (pushtime_end != null) {
			sql_list.append("and sendtime <='"+pushtime_end+" 00:00:00' ");
			sql_total.append("and sendtime <='"+pushtime_end+" 00:00:00' ");
		}
		
		if (start != null) {
			sql_list.append("ORDER BY id DESC LIMIT " + start + "," + length);
		} else {
			sql_list.append("ORDER BY id DESC ");
		}
		
		List<PushMessageVO> list = null;
		
		try {
			list = dao.list(sql_list.toString(), PushMessageVO.class);
			int count = dao.getInt(sql_total.toString());
			pageResponse.setITotalRecords(count);
			pageResponse.setITotalDisplayRecords(count);
//			发送状态status是不准确的。需要查推送任务表(这里没有推送表的数据库连接)
			for (PushMessageVO pushMessageVO : list) {
				
				PushMessageTask task = dao.get("SELECT t.status ,p.name productName FROM push_message_task t ,loan.comm_product_prdid p WHERE t.id = ? AND t.sendproduct = p.prdid" ,PushMessageTask.class, pushMessageVO.getPushid());
				
				if(task != null) {
					pushMessageVO.setTask_sendproduct(task.getProductName());
					
					String status_str = "";
					switch (task.getStatus()) {
					case 0 :
						status_str = "未发送";
						break;
					case 1 :
						status_str = "等待发送";
						break;
					case 2 :
						status_str = "发送中";
						break;
					case 3 :
						status_str = "已发送";
						break;
					case 4 :
						status_str = "已取消";
						break;
						
					default :
						break;
					}
					pushMessageVO.setStatus(status_str);
				}
				String content_tmp = pushMessageVO.getContent();
				if ("CPS".equals(content_tmp)) {
					pushMessageVO.setContent("CPS");
				} else if ("daikuang".equals(content_tmp)) {
					pushMessageVO.setContent("贷款");
				}else if ("chexian".equals(content_tmp)) {
					pushMessageVO.setContent("车险");
				}else if ("jiayouweizhang".equals(content_tmp)) {
					pushMessageVO.setContent("加油违章");
				}else if ("zhidemai".equals(content_tmp)) {
					pushMessageVO.setContent("值得买");
				}else if ("faxianwenzhang".equals(content_tmp)) {
					pushMessageVO.setContent("发现文章");
				}else if ("qita".equals(content_tmp)) {
					pushMessageVO.setContent("其他");
				}
			}	
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public String editRecond(Map<String, Object> paramsMap) {
		return null;
	}

	@Override
	public void editPage(Map<String, Object> paramsMap) {
		String id = (String) paramsMap.get("id");
		String sql = "SELECT * FROM push_message_record WHERE id = ?";
		String sql_task = "select content task_content, createtime task_createtime, sendtime task_sendtime, platfrom task_platform, sendproduct task_sendproduct, sendtype task_sendtype, senduserid task_senduserid, endtime task_endtime, isocontent task_ioscontent, provinceid task_provinceid, tags task_tags, htmlUrl task_htmlUrl from push_message_task where id = ?";
		try {
			List<PushMessageVO> list = dao.list(sql, PushMessageVO.class, id);
			PushMessageVO vo = list.get(0);
			List<PushMessageVO> list_task = dao.list(sql_task, PushMessageVO.class, vo.getPushid());
			
			PushMessageVO vo_task = list_task.get(0);
			paramsMap.put("push_content", vo.getContent());
			paramsMap.put("ios_content", vo.getIos_content());
			paramsMap.put("createtime", vo_task.getTask_createtime());
			paramsMap.put("sendtime", vo_task.getTask_sendtime());
			paramsMap.put("platform", vo_task.getTask_platform());
			paramsMap.put("sendproduct", vo_task.getTask_sendproduct());
			paramsMap.put("sendtype", vo_task.getTask_sendtype());
			paramsMap.put("senduserid", vo_task.getTask_senduserid());
			paramsMap.put("endtime", vo_task.getTask_endtime());
			paramsMap.put("ioscontent", vo_task.getTask_ioscontent());
			paramsMap.put("provinceid", vo_task.getTask_provinceid());
			paramsMap.put("tags", vo_task.getTask_tags());
			
			String task_content = vo_task.getTask_content();
			if (task_content != null) {
				JsonElement jsonElement = new JsonParser().parse(task_content);
				JsonElement icon_tmp = jsonElement.getAsJsonObject().get("icon");
				if (icon_tmp != null) {
					paramsMap.put("icon", icon_tmp.getAsString());
				}
				JsonElement title_tmp = jsonElement.getAsJsonObject().get("title");
				if (title_tmp != null) {
					paramsMap.put("title", title_tmp.getAsString());
				}
				JsonElement content_tmp = jsonElement.getAsJsonObject().get("content");
				if (content_tmp != null) {
					paramsMap.put("content", content_tmp.getAsString());
				}
				JsonElement showType_tmp = jsonElement.getAsJsonObject().get("showType");
				if (showType_tmp != null) {
					paramsMap.put("showType", showType_tmp.getAsString());
				}
				JsonElement notifyType_tmp = jsonElement.getAsJsonObject().get("notifyType");
				if (notifyType_tmp != null) {
					paramsMap.put("notifyType", notifyType_tmp.getAsString());
				}
				JsonElement responseType_tmp = jsonElement.getAsJsonObject().get("responseType");
				if (responseType_tmp != null) {
					paramsMap.put("responseType", responseType_tmp.getAsString());
				}
				JsonElement responseParams_tmp = jsonElement.getAsJsonObject().get("responseParams");
				if (responseParams_tmp != null) {
					JsonElement operate_tmp = responseParams_tmp.getAsJsonObject().get("operate");
					if (operate_tmp != null) {
						paramsMap.put("operate", operate_tmp.getAsString());
					}
					JsonElement launch_tmp = responseParams_tmp.getAsJsonObject().get("launch");
					if (launch_tmp != null) {
						paramsMap.put("launch", launch_tmp.getAsString());
					}
					JsonElement operateParams_tmp = responseParams_tmp.getAsJsonObject().get("operateParams");
					if (operateParams_tmp != null) {
						JsonElement operateParams_imageList = operateParams_tmp.getAsJsonObject().get("imageList");
						if (operateParams_imageList != null) {
							paramsMap.put("operateParams_imageList", operateParams_imageList.getAsString());
						}
						JsonElement operateParams_time = operateParams_tmp.getAsJsonObject().get("time");
						if (operateParams_time != null) {
							paramsMap.put("operateParams_time", operateParams_time.getAsString());
						}
						JsonElement operateParams_type = operateParams_tmp.getAsJsonObject().get("type");
						if (operateParams_type != null) {
							paramsMap.put("operateParams_type", operateParams_type.getAsString());
						}
						JsonElement operateParams_index = operateParams_tmp.getAsJsonObject().get("index");
						if (operateParams_index != null) {
							paramsMap.put("operateParams_index", operateParams_index.getAsString());
						}
						JsonElement operateParams_state = operateParams_tmp.getAsJsonObject().get("state");
						if (operateParams_state != null) {
							paramsMap.put("operateParams_state", operateParams_state.getAsString());
						}
						JsonElement operateParams_tabid = operateParams_tmp.getAsJsonObject().get("tabid");
						if (operateParams_tabid != null) {
							paramsMap.put("operateParams_tabid", operateParams_tabid.getAsString());
						}
						JsonElement operateParams_text = operateParams_tmp.getAsJsonObject().get("text");
						if (operateParams_text != null) {
							paramsMap.put("operateParams_text", operateParams_text.getAsString());
						}
						JsonElement operateParams_starttime = operateParams_tmp.getAsJsonObject().get("starttime");
						if (operateParams_starttime != null) {
							paramsMap.put("operateParams_starttime", operateParams_starttime.getAsString());
						}
						JsonElement operateParams_endtime = operateParams_tmp.getAsJsonObject().get("endtime");
						if (operateParams_endtime != null) {
							paramsMap.put("operateParams_endtime", operateParams_endtime.getAsString());
						}
						JsonElement operateParams_pop_img_url = operateParams_tmp.getAsJsonObject().get("pop_img_url");
						if (operateParams_pop_img_url != null) {
							paramsMap.put("operateParams_pop_img_url", operateParams_pop_img_url.getAsString());
						}
						JsonElement operateParams_msg_center_show = operateParams_tmp.getAsJsonObject().get("msg_center_show");
						if (operateParams_msg_center_show != null) {
							paramsMap.put("operateParams_msg_center_show", operateParams_msg_center_show.getAsString());
						}
						JsonElement operateParams_action = operateParams_tmp.getAsJsonObject().get("action");
						if (operateParams_action != null) {
							paramsMap.put("operateParams_action", operateParams_action.getAsString());
						}
						JsonElement operateParams_value = operateParams_tmp.getAsJsonObject().get("value");
						if (operateParams_value != null) {
							paramsMap.put("operateParams_value", operateParams_value.getAsString());
						}
						JsonElement operateParams_resident = operateParams_tmp.getAsJsonObject().get("resident");
						if (operateParams_resident != null) {
							paramsMap.put("operateParams_resident", operateParams_resident.getAsString());
						}
						JsonElement operateParams_timestamp = operateParams_tmp.getAsJsonObject().get("timestamp");
						if (operateParams_timestamp != null) {
							paramsMap.put("operateParams_timestamp", operateParams_timestamp.getAsString());
						}
					}
					JsonElement launchParams_tmp = responseParams_tmp.getAsJsonObject().get("launchParams");
					if (launchParams_tmp != null) {
						JsonElement launchParams_title = launchParams_tmp.getAsJsonObject().get("title");
						if (launchParams_title != null) {
							paramsMap.put("launchParams_title", launchParams_title.getAsString());
						}
						JsonElement launchParams_showMsgType = launchParams_tmp.getAsJsonObject().get("showMsgType");
						if (launchParams_showMsgType != null) {
							paramsMap.put("launchParams_showMsgType", launchParams_showMsgType.getAsString());
						}
						JsonElement launchParams_tab = launchParams_tmp.getAsJsonObject().get("tab");
						if (launchParams_tab != null) {
							paramsMap.put("launchParams_tab", launchParams_tab.getAsString());
						}
						JsonElement launchParams_id = launchParams_tmp.getAsJsonObject().get("id");
						if (launchParams_id != null) {
							paramsMap.put("launchParams_id", launchParams_id.getAsString());
						}
						JsonElement launchParams_servicetype = launchParams_tmp.getAsJsonObject().get("servicetype");
						if (launchParams_servicetype != null) {
							paramsMap.put("launchParams_servicetype", launchParams_servicetype.getAsString());
						}
						JsonElement launchParams_serviceType = launchParams_tmp.getAsJsonObject().get("serviceType");
						if (launchParams_serviceType != null) {
							paramsMap.put("launchParams_serviceType", launchParams_serviceType.getAsString());
						}
						JsonElement launchParams_car_num = launchParams_tmp.getAsJsonObject().get("car_num");
						if (launchParams_car_num != null) {
							paramsMap.put("launchParams_car_num", launchParams_car_num.getAsString());
						}
						JsonElement launchParams_eng_num = launchParams_tmp.getAsJsonObject().get("eng_num");
						if (launchParams_eng_num != null) {
							paramsMap.put("launchParams_eng_num", launchParams_eng_num.getAsString());
						}
						JsonElement launchParams_shelf_num = launchParams_tmp.getAsJsonObject().get("shelf_num");
						if (launchParams_shelf_num != null) {
							paramsMap.put("launchParams_shelf_num", launchParams_shelf_num.getAsString());
						}
						JsonElement launchParams_owner_name = launchParams_tmp.getAsJsonObject().get("owner_name");
						if (launchParams_owner_name != null) {
							paramsMap.put("launchParams_owner_name", launchParams_owner_name.getAsString());
						}
						JsonElement launchParams_owner_phone = launchParams_tmp.getAsJsonObject().get("owner_phone");
						if (launchParams_owner_phone != null) {
							paramsMap.put("launchParams_owner_phone", launchParams_owner_phone.getAsString());
						}
						JsonElement launchParams_registerno = launchParams_tmp.getAsJsonObject().get("registerno");
						if (launchParams_registerno != null) {
							paramsMap.put("launchParams_registerno", launchParams_registerno.getAsString());
						}
						JsonElement launchParams_city = launchParams_tmp.getAsJsonObject().get("city");
						if (launchParams_city != null) {
							paramsMap.put("launchParams_city", launchParams_city.getAsString());
						}
						JsonElement launchParams_productId = launchParams_tmp.getAsJsonObject().get("productId");
						if (launchParams_productId != null) {
							paramsMap.put("launchParams_productId", launchParams_productId.getAsString());
						}
						JsonElement launchParams_merchantId = launchParams_tmp.getAsJsonObject().get("merchantId");
						if (launchParams_merchantId != null) {
							paramsMap.put("launchParams_merchantId", launchParams_merchantId.getAsString());
						}
						JsonElement launchParams_isaddpoint = launchParams_tmp.getAsJsonObject().get("isaddpoint");
						if (launchParams_isaddpoint != null) {
							paramsMap.put("launchParams_isaddpoint", launchParams_isaddpoint.getAsString());
						}
						JsonElement launchParams_beforeClickImgList = launchParams_tmp.getAsJsonObject().get("beforeClickImgList");
						if (launchParams_beforeClickImgList != null) {
							paramsMap.put("launchParams_beforeClickImgList", launchParams_beforeClickImgList.getAsString());
						}
						JsonElement htmlUrl_tmp = launchParams_tmp.getAsJsonObject().get("htmlUrl");
						if (htmlUrl_tmp != null) {
							paramsMap.put("htmlUrl", vo_task.getTask_htmlUrl());
						}
						JsonElement withHead_tmp = launchParams_tmp.getAsJsonObject().get("withHead");
						if (withHead_tmp != null) {
							paramsMap.put("withHead", withHead_tmp.getAsString());
						}
						JsonElement showToolbar_tmp = launchParams_tmp.getAsJsonObject().get("showToolbar");
						if (showToolbar_tmp != null) {
							paramsMap.put("showToolbar", showToolbar_tmp.getAsString());
						}
						JsonElement clearTop_tmp = launchParams_tmp.getAsJsonObject().get("clearTop");
						if (clearTop_tmp != null) {
							paramsMap.put("clearTop", clearTop_tmp.getAsString());
						}
						JsonElement canBlockNetworkImg_tmp = launchParams_tmp.getAsJsonObject().get("canBlockNetworkImg");
						if (canBlockNetworkImg_tmp != null) {
							paramsMap.put("canBlockNetworkImg", canBlockNetworkImg_tmp.getAsString());
						}
						JsonElement reloadWhenLogin_tmp = launchParams_tmp.getAsJsonObject().get("reloadWhenLogin");
						if (reloadWhenLogin_tmp != null) {
							paramsMap.put("reloadWhenLogin", reloadWhenLogin_tmp.getAsString());
						}
						JsonElement takeOverBackPressed_tmp = launchParams_tmp.getAsJsonObject().get("takeOverBackPressed");
						if (takeOverBackPressed_tmp != null) {
							paramsMap.put("takeOverBackPressed", takeOverBackPressed_tmp.getAsString());
						}
						JsonElement callbackWhenResumeAndPause_tmp = launchParams_tmp.getAsJsonObject().get("callbackWhenResumeAndPause");
						if (callbackWhenResumeAndPause_tmp != null) {
							paramsMap.put("callbackWhenResumeAndPause", callbackWhenResumeAndPause_tmp.getAsString());
						}
						JsonElement showTitle_tmp = launchParams_tmp.getAsJsonObject().get("showTitle");
						if (showTitle_tmp != null) {
							paramsMap.put("showTitle", showTitle_tmp.getAsString());
						}
						JsonElement injectCss_tmp = launchParams_tmp.getAsJsonObject().get("injectCss");
						if (injectCss_tmp != null) {
							paramsMap.put("injectCss", injectCss_tmp.getAsString());
						}
					}
				}
			}
			
		} catch (AppException e) {
			e.printStackTrace();
		} 
	}

	@Override
	public void deleteRecord(Map<String, Object> paramsMap) {
		
		// 删除任务操作，根据pushid调用暂停接口
		String id = (String) paramsMap.get("id");
		try {
			Integer pushid = dao.getInt("SELECT pushid FROM push_message_record WHERE id = ?", id);
			
			FormData fd_stop = new FormData();
			JsonObject stop_obj = new JsonObject();
			stop_obj.add("phead", JSONUtils.toJsonObject(new Phead()));
			stop_obj.addProperty("id", pushid);
			stop_obj.addProperty("op", 3);
			fd_stop.addParam("handle", "0");
			fd_stop.addParam("data", stop_obj.toString());
			fd_stop.addParam("shandle", "1");
			PostData pd_stop = new PostData(fd_stop);
			
			String autoPausePostUrl = Constant.COMMON_HOST + "/push_service/common?funid=1&rd=" + System.currentTimeMillis();
			HttpResult httpResult2 = HttpClientUtil.post(autoPausePostUrl, pd_stop);
			String result = ZipUtil.unCompressData(httpResult2.getData());
			LogService.info(result);
			
			dao.update("update push_message_task set status = '4' where id = ?", pushid);
			dao.delete("delete from push_message_record where id = ?", Integer.parseInt(id));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	
	}

}
